package com.xs.ahoi.hcxs.utils.tts;

import android.content.Context;

import com.tencent.qcloudtts.LongTextTTS.LongTextTtsController;
import com.tencent.qcloudtts.VoiceLanguage;
import com.tencent.qcloudtts.callback.TtsExceptionHandler;
import com.tencent.qcloudtts.exception.TtsNotInitializedException;
import com.xs.ahoi.hcxs.dao.ConfigDao;
import com.xs.ahoi.hcxs.listener.TencentTtsListener;
import com.xs.ahoi.hcxs.utils.LogUtil;
import com.xs.ahoi.hcxs.utils.StringSplitUtils;
import com.xs.ahoi.hcxs.utils.StringUtils;
import com.xs.ahoi.hcxs.utils.ToastUtil;

import java.util.List;


/**
 * 腾讯语音合成工具
 *
 * @author: fuhuichao
 * @date: 2022/5/10 2:47 下午
 */
public class TtsTencentUtil extends AbstractTTS {
    private static TtsTencentUtil instance;
    private static final Long APP_ID = 1300217350L;
    private static final String SECRET_ID = "AKIDNopFh3PnBZzOj0KUdfhdN1cCnNvWzPjv";
    private static final String SECRET_KEY = "KUTVNH6zmV4LOK3bMwJWaWFpY8Yq01uo";

    private LongTextTtsController mTtsController;
    private boolean isComplete = true, restart = true;

    TencentTtsListener listener = new TencentTtsListener() {
        @Override
        public void onTTSPlayEnd() {
            LogUtil.e("onTTSPlayEnd");
            if (ttsListener != null && ttsListener.isPlaying()) {
                restart = isComplete = true;
                next();
            } else if (APP_PLAYING) {
                appTTSListener.finish();
            }
        }
    };

    private final TtsExceptionHandler mTtsExceptionHandler = e -> {
        LogUtil.e("错误发生：" + e.getMessage());
        listener.onTTSPlayEnd();
    };

    private TtsTencentUtil(Context context) {
        init(context);
    }

    public static TtsTencentUtil getInstance() {
        return instance;
    }

    public static TtsTencentUtil createInstance(Context context) {
        if (instance == null) {
            instance = new TtsTencentUtil(context);
        }
        return instance;
    }

    // 初始化
    public void init(Context context) {
        // 构造LongTextTtsController，支持长文本播放，可暂停/恢复播放。非流式api，故建议文本中第一句话不要设的太长
        mTtsController = new LongTextTtsController();

        // 直接鉴权
        mTtsController.init(context, APP_ID, SECRET_ID, SECRET_KEY);

        // 设置参数
        setParams();
    }

    public boolean start() {
        if (restart || lineIndexs.isEmpty()) {
            String text = getSpeakText();
            if (StringUtils.isEmpty(StringUtils.replaceWrap(text))) {
                next();
                return true;
            }
            speakText(text);
            ttsListener.refreshPage();
            restart = false;
        } else {
            resume();
        }
        return true;
    }

    private void resume() {
        if (restart || isComplete) {
            ttsListener.nextPage();
            start();
        } else {
            if (mTtsController != null) {
                mTtsController.resume();
            }
        }
    }

    public boolean speakText(String text) {
        try {
            mTtsController.startTts(StringSplitUtils.split(text), mTtsExceptionHandler, listener);
        } catch (TtsNotInitializedException e) {
            print("腾讯tts初始化失败", true);
        }
        return true;
    }

    public void onlyStop() {
        mTtsController.stop();
    }

    public void stop() {
        lineIndexs.clear();
        mTtsController.stop();
    }

    public void pause() {
        isComplete = false;
        mTtsController.pause();
    }

    public void reset() {
        stop();
        restart = true;
        isComplete = false;
        lineIndexPrev = lineIndexCurrent = 0;
    }

    private void print(String msg) {
        print(msg, false);
    }

    private void print(String msg, boolean toast) {
        LogUtil.e(msg);
        if (toast) {
            ToastUtil.show(msg);
        }
    }

    // 设置参数
    private void setParams() {
        //设置ProjectId 不设置默认使用0，说明：项目功能用于按项目管理云资源，可以对云资源进行分项目管理，详情见 https://console.cloud.tencent.com/project
        mTtsController.setProjectId(0);
        //设置语言
        mTtsController.setVoiceLanguage(VoiceLanguage.VOICE_LANGUAGE_CHINESE.getNum());
        changeTtsParam();
    }

    public void changeTtsParam() {
        //设置语速
        mTtsController.setVoiceSpeed(ConfigDao.getInstance().getTtsSpeed());
        //设置音色
        mTtsController.setVoiceType(ConfigDao.getInstance().getTtsSpeaker());
    }

}
